import os
import json
import random

from flask import render_template, request, make_response, jsonify, session
from flask.helpers import flash, url_for
from werkzeug.utils import redirect

from . import views
from config import site_config_file_name, site_config_json, Config
from ..tools.utils import md5_fn
from ..tools.file import write_file, create_path
from ..tools.service import login_required, logout
from ..tools.validate import validate_img_ext, validate_video_ext
from ..models.mysql import Mysql


@views.route("/admin/site", methods=["GET", "POST"])
@views.route("/admin/", methods=["GET", "POST"])
@login_required
def admin():
    if request.method == "POST":
        site_name = request.form.get('site_name')
        if site_name:
            site_config_json['name'] = site_name

        to_quote = request.form.get('to_quote')
        if to_quote:
            site_config_json['to_quote'] = to_quote

        index_bg = request.form.get('index_bg')
        if index_bg:
            site_config_json['index_bg'] = index_bg

        video_url = request.form.get('video_url')
        if video_url:
            site_config_json['video_url'] = video_url

        footer = request.form.get('footer')
        if footer:
            site_config_json['footer'] = footer
        flash("修改成功！", "success")
        write_file(site_config_file_name, json.dumps(site_config_json))

    return render_template('admin/site.html')


@views.route("/admin/links")
@login_required
def admin_links():

    return render_template('admin/links.html')


@views.route("/admin/article", methods=["GET", "POST"])
@login_required
def admin_article():

    return render_template('admin/article.html')


@views.route("/admin/info", methods=["GET", "POST"])
@login_required
def admin_info():
    if request.method == "POST" and request.form.get("rand") == session.get("rand"):
        image = request.files.get('url_image')
        desc_image = request.form.get('desc_image')
        if image and validate_img_ext(image.filename):
            fn = md5_fn(image.filename)
            fp = os.path.join(create_path(
                Config.STATIC_PATH, "upload", "images"), fn)
            url = os.path.join(Config.STATIC_URL, "upload", "images", fn)
            image.save(fp)
            with Mysql(True) as conn:
                conn.cursor.execute(
                    """INSERT INTO images(`url`, `desc`) VALUES(%s, %s);""", (url, desc_image))
            flash("图片上传成功！！", "success")

        video = request.files.get('url_video')
        desc_video = request.form.get('desc_video')
        if video and validate_video_ext(video.filename):
            fn = md5_fn(video.filename)
            fp = os.path.join(create_path(
                Config.STATIC_PATH, "upload", "videos"), fn)
            url = os.path.join(Config.STATIC_URL, "upload", "videos", fn)
            video.save(fp)
            with Mysql(True) as conn:
                conn.cursor.execute(
                    """INSERT INTO videos(`url`, `desc`) VALUES(%s, %s);""", (url, desc_video))
            flash("视频上传成功！！", "success")

    rand = random.randint(100000, 999999)
    session['rand'] = str(rand)
    with Mysql() as conn:
        conn.cursor.execute(
            """SELECT * FROM images WHERE `deleted`=0 order by created DESC """)
        img_list = conn.cursor.fetchall()

    with Mysql() as conn:
        conn.cursor.execute(
            """SELECT * FROM videos WHERE `deleted`=0 order by created DESC """)
        video_list = conn.cursor.fetchall()

    return render_template('admin/info.html', img_list=img_list, video_list=video_list, rand=rand)


@views.route("/admin/info", methods=["DELETE"])
@login_required
def admin_info_del():
    data = json.loads(request.data)
    with Mysql(True) as conn:
        if data["type"] == "video":
            # conn.cursor.execute("""DELETE FROM videos WHERE id=%s""", (data["id"]))
            conn.cursor.execute(
                """UPDATE videos SET `deleted`=1 WHERE id=%s""", (data["id"]))
        elif data["type"] == "img":
            conn.cursor.execute(
                """UPDATE images SET `deleted`=1 WHERE id=%s""", (data["id"]))
        flash("删除成功！！", "success")

    return jsonify(
        code=0,
        data=True
    )


@views.route("/admin/logout")
@login_required
def admin_logout():
    resp = make_response(redirect(url_for("views.index")))
    logout(resp)
    flash("退出成功！！", "success")
    return resp
